package Demo;

public class MyBlockingQueue {
        private int[] elem;
        private volatile int usedSize = 0;// 有效个数
        private volatile int front = 0;
        private volatile int rear = 0;
        public MyBlockingQueue(){
            this.elem = new int[10];
        }
        public MyBlockingQueue(int k){
            this.elem = new int[k];
        }
        /**
         * 入队
         * @param val
         * @return
         */
        public void put(int val) throws InterruptedException {
            synchronized (this) {
                // 判断队列是否满了
                while (usedSize >= elem.length){
                    this.wait();
                }
                // 进行入队列操作
                elem[rear] = val;
                rear++;
                if (rear >= elem.length){
                    rear = 0;
                }
                usedSize++;
                this.notify();
            }
        }
        /**
         * 出队
         * @return
         */
        public Integer take() throws InterruptedException {
            synchronized (this) {
                while (usedSize == 0){
                    this.wait();
                }
                int ret = elem[front];
                front++;
                if (front >= elem.length){
                    front = 0;
                }
                usedSize--;
                this.notify();
                return ret;
            }
        }
}
